package mrpanyu.guitool.deploy;

import java.io.File;
import java.util.ArrayList;

import com.alibaba.fastjson2.JSON;

import mrpanyu.guitool.base.annotation.Action;
import mrpanyu.guitool.base.annotation.OnLoad;
import mrpanyu.guitool.base.annotation.Parameter;
import mrpanyu.guitool.base.annotation.ToolModel;
import mrpanyu.guitool.base.model.ParameterType;
import mrpanyu.guitool.base.model.Tool;
import mrpanyu.guitool.base.util.CommonUtils;

@ToolModel(displayName = "部署自动化工具", description = "部署自动化工具")
public class DeployTool {

	@Parameter(displayName = "根目录", order = 0, type = ParameterType.DIRECTORY)
	private File baseDir;

	@Parameter(displayName = "选择任务", order = 1, type = ParameterType.SELECT, options = {})
	private String taskName;

	private DeployConfig config;

	@OnLoad
	public void onLoad(Tool tool) throws Exception {
		String json = CommonUtils.readString(new File("deploy-config.json"), "UTF-8");
		config = JSON.parseObject(json, DeployConfig.class);
		tool.getParameter("taskName").setOptions(new ArrayList<>(config.getTasks().keySet()));
	}

	@Action(displayName = "执行", order = 0)
	public void execute(Tool tool) {
		tool.clearMessages();
		if (baseDir == null || !baseDir.isDirectory()) {
			tool.errorMessage("请选择根目录");
			return;
		}
		DeployTask task = config.getTasks().get(taskName);
		if (task == null) {
			tool.warnMessage("请选择任务");
			return;
		}
		try {
			executeTask(tool, taskName, task);
		} catch (Exception e) {
			tool.errorMessage(e);
		}
	}

	private void executeTask(Tool tool, String taskName, DeployTask task) throws Exception {
		tool.infoMessage("开始执行任务: " + taskName);
		if (task.getDependTasks() != null) {
			for (String depName : task.getDependTasks()) {
				DeployTask depTask = config.getTasks().get(depName);
				executeTask(tool, depName, depTask);
			}
		}

		if (task.getUpload() != null) {
			JSchHelper helper = new JSchHelper(tool, config.getServers().get(task.getServer()));
			helper.uploadFile(new File(baseDir, task.getUpload().getLocalPath()), task.getUpload().getRemotePath());
		}

		if (task.getCommands() != null) {
			JSchHelper helper = new JSchHelper(tool, config.getServers().get(task.getServer()));
			helper.executeCommands(task.getCommands());
		}

		tool.infoMessage("完成执行任务: " + taskName);
	}

}
